<template>
  <div class="setRole">
    <!--分配权限  -->
    <el-dialog :title="'为[' + roleName + ']分配权限'" :visible="showRole" @close="$emit('update:showRole', false)">
      <el-tree
        ref="mytree"
        :data="list"
        :props="{ label: 'name' }"
        default-expand-all
        show-checkbox
        check-strictly
        node-key="id"
      ></el-tree>
      <div slot="footer">
        <el-button @click="$emit('update:showRole', false)">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAllPerApi } from '@/api/permission'
import { getRoleApi, setRoleApi } from '@/api/setting'
export default {
  props: ['roleName', 'showRole'],
  data() {
    return {
      list: [],
      // 当前数据id
      id: ''
    }
  },
  methods: {
    // 提交设置权限
    async submit() {
      const roleIds = this.$refs.mytree.getCheckedKeys()
      await setRoleApi({
        id: this.id,
        permIds: roleIds
      })
      this.$emit('update:showRole', false)
      this.$message.success('修改权限成功')
    },
    // 定义方法得到默认权限
    async getRoleId(id) {
      this.id = id
      const res = await getRoleApi(id)
      // 得到权限
      const roleIds = res.data.data.permIds
      // 将数据给tree组件
      this.$refs.mytree.setCheckedKeys(roleIds)
    },
    // 得到所有权限
    async getAllPer() {
      const res = await getAllPerApi()
      this.list = this.turnData(res.data.data, '0')
    },
    turnData(arr, pid) {
      const res = []
      arr.forEach(item => {
        if (item.pid === pid) {
          const children = this.turnData(arr, item.id)
          item.children = children
          res.push(item)
        }
      })
      return res
    }
  },
  created() {
    this.getAllPer()
  }
}
</script>

<style></style>
